import axios from 'axios'
import config from '../config'

export default class BaseService {
  root = '/'

  create (entity) {
    return axios.post(config.SERVER_URL + this.root, {...entity, responseType: 'json'})
      .then(resp => resp.data)
  }

  update (entity) {
    return axios.put(config.SERVER_URL + this.root, {...entity, responseType: 'json'})
      .then(resp => resp.data)
  }

  delete (id) {
    return axios.delete(config.SERVER_URL + this.root + '/' + id, {responseType: 'json'})
      .then(resp => resp.data)
  }

  ps (page, query = '', pageSize = config.PAGE_SIZE) {
    return axios.get(config.SERVER_URL + `${this.root}-ps?page=${page}&size=${pageSize}&query=${query}`, {responseType: 'json'})
      .then(resp => {
        return {
          dataCount: parseInt(resp.headers['x-total-count'], 10),
          data: resp.data
        }
      })
  }

  search (query = '') {
    return axios.get(config.SERVER_URL + `${this.root}?query=${query}`, {responseType: 'json'})
      .then(resp => resp.data)
  }

  findOne (id) {
    return axios.get(config.SERVER_URL + this.root + '/' + id, {responseType: 'json'})
      .then(resp => resp.data)
  }

  get (path) {
    return axios.get(config.SERVER_URL + path, {responseType: 'json'})
  }

  post (path, entity) {
    return axios.post(config.SERVER_URL + path, {...entity, responseType: 'json'})
  }

  put (path, entity) {
    return axios.put(config.SERVER_URL + path, {...entity, responseType: 'json'})
  }
}
